﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Submarines;
using GameClient;
using System.Net.Sockets;
using System.Threading;

namespace Submarines
{
    public partial class frmLogin : Form
    {
       
        delegate void LogInCallback(bool status);
        delegate void WaitWindowCloseCallBack();
     
        frmMain _frmMain = new frmMain();

        frmWait _wait = new frmWait(10, "Login");

        public frmLogin()
        {
            InitializeComponent();
            Thread th = new Thread(new ThreadStart(EventListiner));
            th.IsBackground = true;
            th.Start();
            
        }

        #region Local_events

        void frmLogin_Load(object sender, EventArgs e)
        {
            cmbLang.SelectedIndex = 0;
            lblUser.BackColor = Color.Transparent;
            lblPass.BackColor = Color.Transparent;
            lblUserName.BackColor = Color.Transparent;
            DialogResult dr;
            Diag.AddLog(this.Name, "Form loaded");
            try
            {
                //GameClient.Client.LoginAnswer += new Client.GameReceiveHandler(Client_LoginAnswer);
                //GameClient.Client.LogoutAnswer += new Client.GameReceiveHandler(Client_LogoutAnswer);
                Diag.AddLog(this.Name, "Server OK");
            }
            catch (TypeInitializationException)
            {
                dr = MessageBox.Show("Server is DOWN","BattleShip",MessageBoxButtons.AbortRetryIgnore,MessageBoxIcon.Warning);
                if (dr == DialogResult.Abort)
                    this.Close();
                else if (dr == DialogResult.Retry)
                {
                    try
                    {
                        GameClient.Client.LoginAnswer += new Client.GameReceiveHandler(Client_LoginAnswer);
                    }
                    catch (TypeInitializationException)
                    {
                        MessageBox.Show("Server still not answering","BattleShip");
                        this.Close();
                    }
                }
                else if (dr == DialogResult.Ignore)
                {
                    Diag.AddLog(this.Name, "Run without server");
                }

            }
        }

        private void cmbLanguage_SelectedIndexChanged(object sender, EventArgs e)
        {
            Global._Language = cmbLang.SelectedItem.ToString();
            Lang.Language(this,typeof(frmLogin));
        }

        private void txtPassword_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13)
                btnLogIn_Click(null, null);
        }

        private void btnLogIn_Click(object sender, EventArgs e)
        {
                string _mess;
                _mess = "";
                if (Global._Language == "Русский")
                    _mess = "Авторизация";
                else if (Global._Language == "עברית")
                    _mess = "כניסה";
                else
                    _mess = "In";
              //if (btnLogIn.Text.Contains(_mess))
                if (!Global.LogedIn)
                {
                    try
                    {
                        if (txtUserName.Text.Length>0)
                        {
                            Diag.AddLog(this.Name, "Client.Login sent");
                            GameClient.Client.Login(txtUserName.Text, txtPassword.Text);
                            // _waitToLogin.ShowWindow();
                            
                            _wait.ShowDialog();
                        }
                    }
                    catch (SocketException se)
                    {
                        Diag.AddLog(this.Name, se.Message, System.Diagnostics.EventLogEntryType.FailureAudit);
                        MessageBox.Show("Server is DOWN", "BattleShip", MessageBoxButtons.AbortRetryIgnore, MessageBoxIcon.Warning);
                    }
                }
                else
                {
                    Diag.AddLog(this.Name, "Client.Logout sent");
                    GameClient.Client.Logout();
                    LogIn(false);
                }
        }

        private void btnMain_Click(object sender, EventArgs e)
        {
            frmMain main = new frmMain();
            main.ShowDialog();
        }

        private void btnLocGame_Click(object sender, EventArgs e)
        {
            Global._Local = true;
            frmGame game = new frmGame();
            game.ShowDialog();
        }

        //private void frmLogin_MouseMove(object sender, MouseEventArgs e)
        //{
        //    if (start)
        //    {
        //        _controlCordinate_start = this.Location;
        //        start = false;
        //    }
            
        //    if ((e.Button & MouseButtons.Left) == MouseButtons.Left)
        //    {
        //        _mouseCordinate_end = MousePosition;
        //        this.Location = new Point(_controlCordinate_start.X - (_mouseCordinate_start.X - _mouseCordinate_end.X), _controlCordinate_start.Y - (_mouseCordinate_start.Y - _mouseCordinate_end.Y));
        //        _mouseCordinate_start = MousePosition;
        //        _controlCordinate_start = this.Location;
        //    }
        //    else
        //        _mouseCordinate_start = MousePosition;
        //}

        private void frmLogin_FormClosing(object sender, FormClosingEventArgs e)
        {
            Diag.AddLog(this.Name, "Client.Logout sent");
            if (Global.LogedIn)
                GameClient.Client.Logout();
            Environment.Exit(0);
        }

     
        #endregion

        #region Push_Events

      
        void Client_LoginAnswer(object sender, ClientEventArgs e)
        {
            this.Enabled = true;
            Diag.AddLog(this.Name, "Client_LoginAnswer=" + e.BoolValue.ToString());
            if (e.BoolValue)
            {
                CloseWaitForm();
                //_waitToLogin.CloseWindow();
                Global._User_name = txtUserName.Text;
                Global._Local = false;
                LogIn(true);
                //_frmMain = new frmMain();
                Thread mainThreaad = new Thread(new ThreadStart(StartMain));
                mainThreaad.IsBackground = true;
                mainThreaad.Start();
                //_frmMain.Show();
            }
            else
            {
                string _mess;
                if (Global._Language == "Русский")
                    _mess = "Неправельные пароль или имя пользователя!";
                else if (Global._Language == "עברית")
                    _mess = "! "+"שם המשתמש או סיסמא לא נכונים";
                else
                    _mess = "Wrong user name or password!";
                MessageBox.Show(_mess);
            }
        }

        void Client_LogoutAnswer(object sender, ClientEventArgs e)
        {
            Diag.AddLog(this.Name, "Client_LogoutAnswer recieved");
            LogIn(false);
        }

        #endregion

        #region Local_Func

        

        void EventListiner()
        {
            GameClient.Client.LoginAnswer += new Client.GameReceiveHandler(Client_LoginAnswer);
            GameClient.Client.LogoutAnswer += new Client.GameReceiveHandler(Client_LogoutAnswer);

        }

        void StartMain()
        {
            _frmMain.ShowDialog();
        }

        void CloseWaitForm()
        {
            if (this.InvokeRequired)
            {
                try
                {
                    WaitWindowCloseCallBack d = new WaitWindowCloseCallBack(CloseWaitForm);
                    this.Invoke(d, new object[] { });
                }
                catch (ObjectDisposedException)
                { }
            }
            else
            {
                _wait.CloseWindow();
            }
        }

        void LogIn(bool status)
        {
            if (this.InvokeRequired)
            {
                LogInCallback d = new LogInCallback(LogIn);
                this.Invoke(d, new object[] { status });
            }
            else
            {
                Global.LogedIn = status;
                lblUserName.Text = txtUserName.Text;
                lblUserName.Visible = status;
                txtUserName.Visible = !status;
                txtUserName.Text = "";
                txtPassword.Visible = !status;
                txtPassword.Text = "";
                lblPass.Visible = !status;
                btnMain.Visible = status;
                string _mess;
                if (status)
                {
                    if (Global._Language == "Русский")
                        _mess = "&Выход";
                    else if (Global._Language == "עברית")
                        _mess = "&יציאה";
                    else
                        _mess = "Log &Out";

                    btnLogIn.Text = _mess;
                }

                else
                {
                    if (Global._Language == "Русский")
                        _mess = "&Авторизация";
                    else if (Global._Language == "עברית")
                        _mess = "&כניסה";
                    else
                        _mess = "Log &In";

                    btnLogIn.Text = _mess;
                    txtUserName.Focus();
                }
                btnLogIn.FlatAppearance.BorderSize = 0;
            }
        }

        #endregion

     

   

       
    }
}
